<template>
  <div>
    <p-modal
      :visible="visible"
      :title="title"
      :width="1000"
      :z-index="1002"
      :mask-closable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div>
        <p-form-model
          :model="form"
          :rules="rules"
          layout="inline"
          :label-col="{ span: 5 }"
        >
          <p-form-model-item label="产品编码">
            <p-input v-model="form.productNo" placeholder="请输入" />
          </p-form-model-item>
          <p-form-model-item label="产品名称">
            <p-input v-model="form.name" placeholder="请输入" />
          </p-form-model-item>

          <p-button type="primary" @click="getList">搜索</p-button>
          <p-form-model-item label="产品状态">
            <SelectDefault
              v-model="form.state"
              class="select"
              code="product_status"
            />
          </p-form-model-item>
          <p-form-model-item label="产品类型 ">
            <SelectDefault v-model="form.type" code="product_type" />
          </p-form-model-item>
          <p-button style="margin-left: auto" @click="handleReset">
            重置
          </p-button>
        </p-form-model>
        <p-button type="primary" @click="getProductAdd">新增产品</p-button>
        <p-table
          class="table-list-container"
          row-key="id"
          :scroll="{ x: '100%', y: 'calc(100vh - 450px)' }"
          :columns="columns"
          bordered
          :loading="loading"
          :pagination="paginationMixin"
          :row-selection="rowSelectionMixin"
          :data-source="dataSource"
          @change="handleTableChange"
        >
          <a
            slot="productNo"
            slot-scope="text, record"
            @click="handleNumberClick(record)"
          >
            {{ text }}
          </a>
        </p-table>
      </div>
    </p-modal>
  </div>
</template>

<script>
import {
  postProductList,
  postleadsProduct,
  postleadsProductList,
} from '@/api/clue.js';
import { postBusinessProduct } from '@/api/business';
import mixinTable from '@/mixins/mixin-table.js';
const defaultForm = {
  productNo: undefined,
  name: undefined,
  state: undefined,
  type: undefined,
};
export default {
  mixins: [mixinTable],
  props: {
    title: {
      type: String,
      default: '选择产品',
    },
    value: {
      type: [String, Number],
      default: undefined,
    },
    index: {
      type: Number,
      default: 0,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    opportunityId: {
      type: [String, Number],
      default: undefined,
    },
    leadsNo: {
      type: [String, Number],
      default: undefined,
    },
    list: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      parentId: '1',
      detail: {},
      planId: undefined,
      asc: true,
      dataList: [],
      form: {
        ...defaultForm,
      },
    };
  },
  computed: {
    stateOptions() {
      return this.$store.state.dictionary.dict['product_status'] || {};
    },
    typeOptions() {
      return this.$store.state.dictionary.dict['product_type'] || {};
    },
    formOptions() {
      return this.$store.state.dictionary.dict['product_from'] || {};
    },
    columns() {
      const columns = [
        {
          align: 'center',
          title: '序号',
          width: 60,
          customRender(t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '产品编码',
          width: 150,
          ellipsis: true,
          dataIndex: 'productNo',
          scopedSlots: { customRender: 'productNo' },
        },
        {
          align: 'center',
          title: '产品名称',
          width: 160,
          ellipsis: true,
          dataIndex: 'name',
        },
        {
          align: 'center',
          title: '产品状态',
          width: 160,
          ellipsis: true,
          dataIndex: 'state',
          customRender: text => this.stateOptions[text],
        },
        {
          align: 'center',
          title: '产品类型',
          dataIndex: 'type',
          width: 160,
          ellipsis: true,
          customRender: text => this.typeOptions[text],
        },
        {
          align: 'center',
          title: '机种',
          width: 160,
          ellipsis: true,
          dataIndex: 'modelName',
        },
        {
          align: 'center',
          title: '出货形态',
          dataIndex: 'form',
          width: 100,
          ellipsis: true,
          customRender: text => this.formOptions[text],
        },
      ];
      return columns;
    },
  },
  watch: {
    visible: {
      handler(val) {
        val && this.getList();
        val && this.getSelect();
      },
    },
    immediate: true,
  },
  created() {},
  methods: {
    getSelect() {
      const codes = this.list.map(item => item.productNo);
      console.log(codes, 'codes');
      this.rowSelectionMixin.getCheckboxProps = record => {
        return {
          props: {
            disabled: record.state === '0' || codes.includes(record.productNo),
          },
        };
      };
    },
    getSearchForm() {
      const page = {
        current: this.paginationMixin.current,
        pageSize: this.paginationMixin.pageSize,
        asc: this.asc,
        column: this.columnKey,
      };
      return {
        ...this.form,
        ...page,
      };
    },
    // 搜索产品列表
    async getList() {
      const form = this.getSearchForm();
      this.loading = true;
      const result = await postProductList(form).finally(
        () => (this.loading = false)
      );
      this.dataSource = result.data.data?.records;
      this.paginationMixin.total = result.data.data?.total;
    },
    // 重置
    handleReset() {
      this.form = { ...defaultForm };
      this.paginationMixin.current = 1;
      this.getList();
    },
    handleCancel() {
      this.$emit('update:visible', false);
      this.rowSelectionMixin.selectedRowKeys = [];
      this.$emit('fresh');
    },
    // 选择产品
    async handleOk() {
      const selectedRowKeys = this.rowSelectionMixin.selectedRowKeys || [];
      if (!selectedRowKeys.length) {
        this.$message.info(
          `请选择关联产品，现有 ${selectedRowKeys.length} 条！`
        );
        return;
      }
      const res = await postleadsProductList({
        leadsNo: this.leadsNo,
        status: '1',
      });
      const selectedInfos = this.rowSelectionMixin.selectedRows
        .filter(item => item.state === '1')
        .map((item, i) => {
          return {
            productNo: item.productNo,
            leadsNo: this.leadsNo,
            opportunityId: this.opportunityId,
            bizType: '1',
          };
        });
      if (!selectedInfos.length) {
        this.$message.info(
          `请选择已启用产品，现有 ${selectedInfos.length} 条！`
        );
        return;
      }
      try {
        await this.$confirm(
          `仅可关联已启用产品，共 ${selectedInfos.length} 条，是否确认？`
        );
        if (this.opportunityId) {
          await postBusinessProduct(selectedInfos);
        } else {
          await postleadsProduct(selectedInfos);
        }
        this.$message.success('关联成功');
        this.handleCancel();
      } catch (error) {
        // console.log('error: ', error);
      }
    },
    // 分页
    handleTableChange(page, filters, sorter, { currentDataSource }) {
      this.asc = sorter.order === 'ascend' ? true : false;
      this.columnKey = sorter.columnKey;
      this.paginationMixin = page;
      this.getList();
    },
    // 编号
    handleNumberClick(record) {
      this.$router.push({
        path: '/product-info',
        query: {
          id: record.id,
        },
      });
    },
    // 新增产品
    getProductAdd() {
      const routeUrl = this.$router.resolve({
        path: '/product-info',
        query: {
          code: 'product',
        },
      });
      window.open(routeUrl.href);
    },
  },
};
</script>

<style lang="less" scoped>
.content-container {
  width: 100%;
  display: flex;
  align-items: center;
  .content {
    display: flex;
    justify-content: center;
    flex: 1;
  }
}
.table-list-container {
  margin-top: 20px;
}
.poros-form {
  box-sizing: border-box;
  background-color: #f7f7f8;
  padding: 10px;
  padding-bottom: 0px;
  width: 100%;
}
.poros-form-item {
  width: 33%;
  margin: 0 30px 10px;
}
/deep/ .poros-form-item-control-wrapper {
  width: calc(100% - 70px);
}
.btn-search {
  margin-right: 16px;
}
/deep/ .select {
  z-index: 9999;
}
</style>
